﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DalGen.Service;
using DalGen.Contracts;
using DalGen.Entity;
using ICSharpCode.TextEditor.Document;
using DalGen.Util;
using System.Threading;

namespace DalGen
{
    public partial class MainForm2 : Form
    {
        IBuilder builder;
        EBuilderInfo info = new EBuilderInfo();

        delegate void SetTreeViewSybDelegate(TreeNode node,string name); 

        public MainForm2(EBuilderInfo entity)
        {
            InitializeComponent();
            info = entity;

			switch (entity.DataBaseType.ToLower())
			{
				case "mysql":
					builder = new MySqlBuilder();
					break;
				case "sqlserver":
					builder = new SqlBuilder();
					break;
			}

           
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            GetAttr();
            builder.ConnectionString = info.ConnectionString;
            DataTable dt = builder.GetAllTables();
            LoadTree(dt);
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < treeView1.Nodes.Count; i++)
            {
                treeView1.Nodes[i].Checked = true;
            }
        }

        private void btnUnSelect_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < treeView1.Nodes.Count; i++)
            {
                treeView1.Nodes[i].Checked = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SetAttr();

            info.Columns = new List<ETableInfo>();
            
            int selectCnt = 0;

            richtxtDebug.Clear();
            this.tabControl1.SelectedTab = this.tabPage1;

            foreach (TreeNode item in treeView1.Nodes)
            {
                if (item.Checked)
                {
                    selectCnt++;
                    richtxtDebug.AppendText("正在生成 " + item.Text+ "\r\n ");
                    Application.DoEvents();

                    info.Columns = builder.GetColumns(info.DataBaseName, item.Text);
                    info.TableName = item.Text;
                    string textEditor = "";

                    #region  生成判断
                    switch (comboBox1.SelectedItem.ToString())
                    {
                        case "Entity":
                            textEditor = builder.BuilderEntity(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;
                        case "Mapping":
                            textEditor = builder.BuilderMap(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "XML");
                            }
                            break;
                        case "IRepository":
                            textEditor = builder.BuilderIRepository(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;
                        case "Repository":
                            textEditor = builder.BuilderRepository(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;
                        case "IService":
                            textEditor = builder.BuilderIService(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;
                        case "Service":
                            textEditor = builder.BuilderService(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;

                        case "ServiceModel":
                            textEditor = builder.BuilderServiceModel(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;
                        default:
                            textEditor = builder.BuilderEntity(info);
                            if (selectCnt == 1)
                            {
                                SetTextEditor(textEditor, "C#");
                            }
                            break;

                    }

                    #endregion




                }
            }


            richtxtDebug.AppendText("生成完成!\r\n ");

            if (selectCnt == 1)
                this.tabControl1.SelectedTab = this.tabPage3;

        }

        private void SetAttr()
        {
            info.ProjectSavePath = txtProjectFolder.Text;
            info.ProjectNameSpace = txtProjectNameSpace.Text;

            info.EntityNameSpace = txtEntityNameSpace.Text;
            info.EntitySavePath = txtEntityFolder.Text;
            info.MapXmlSavePath = txtMapFolder.Text;

            info.IRepositoryNameSpace = txtIRespositoryNameSpace.Text;
            info.IRepositorySavePath = txtIRespositoryFolder.Text;

            info.RepositoryNameSpace = txtRespositoryNameSpace.Text;
            info.RepositorySavePath = txtRespositoryFolder.Text;

            info.IServiceNameSpace = txtIServiceNameSpace.Text;
            info.IServiceSavePath = txtIServiceFolder.Text;

            info.ServiceNameSpace = txtServiceNameSpace.Text;
            info.ServiceSavePath = txtServiceFolder.Text;

            info.ServiceModelNameSpace = txtServiceModelNameSpace.Text;
            info.ServiceModelSavePath = txtServiceModelFolder.Text;


        }

        private void GetAttr()
        {
            txtProjectNameSpace.Text = info.ProjectNameSpace;
            txtProjectFolder.Text = info.ProjectSavePath;
            txtEntityNameSpace.Text = info.EntityNameSpace;
            txtEntityFolder.Text = info.EntitySavePath;
            txtMapFolder.Text = info.MapXmlSavePath;
            txtIRespositoryNameSpace.Text = info.IRepositoryNameSpace;
            txtIRespositoryFolder.Text = info.IRepositorySavePath;
            txtRespositoryNameSpace.Text = info.RepositoryNameSpace;
            txtRespositoryFolder.Text = info.RepositorySavePath;
            txtIServiceNameSpace.Text = info.IServiceNameSpace;
            txtIServiceFolder.Text = info.IServiceSavePath;
            txtServiceNameSpace.Text = info.ServiceNameSpace;
            txtServiceFolder.Text = info.ServiceSavePath;
            txtServiceModelNameSpace.Text = info.ServiceModelNameSpace;
            txtServiceModelFolder.Text = info.ServiceModelSavePath;



        }

        #region 加载子菜单

        private void LoadTree(DataTable dt)
        {
            treeView1.Nodes.Clear();
            for (int i = 0; i < dt.Rows.Count; i++)
                treeView1.Nodes.Add(dt.Rows[i][0].ToString());
            treeView1.CheckBoxes = true;


            ThreadPool.QueueUserWorkItem(LoadTreeSub);

    
        }


        private void LoadTreeSub(object stats)
        {

            foreach (TreeNode item in treeView1.Nodes)
            {

                List<ETableInfo> tableList = builder.GetColumns(info.DataBaseName, item.Text);

                foreach (var entity in tableList)
                {
                    Invoke(new SetTreeViewSybDelegate(SetTreeSub),new object[]{item,entity.ColumnName});
                    //item.Nodes.Add(entity.ColumnName);
                }

            }
        }

        private void SetTreeSub(TreeNode node, string name)
        {
            node.Nodes.Add(name);
            
        }

        #endregion

        private void SetTextEditor(string value, string strategy)
        {
            textEditorControl.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(strategy);
            textEditorControl.Document.TextContent = value;
            textEditorControl.ShowLineNumbers = true;

        }



        private void txtProjectNameSpace_TextChanged(object sender, EventArgs e)
        {
            string namePace = txtProjectNameSpace.Text;
            txtEntityNameSpace.Text = namePace + ".Entity";
            txtIRespositoryNameSpace.Text = namePace + ".Respository";
            txtRespositoryNameSpace.Text = namePace + ".IBatisRepository";
            txtIServiceNameSpace.Text = namePace + ".Service.Contracts";
            txtServiceNameSpace.Text = namePace + ".Service";
            txtServiceModelNameSpace.Text = namePace + ".Service.Model";

        }


        #region 保存路径

        private void btnProjectFolder_Click(object sender, EventArgs e)
        {
            SetSavePath(txtProjectFolder);
        }

        private void btnEntityBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtEntityFolder);
        }

        private void btnMapBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtMapFolder);
        }

        private void btnIRespositoryBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtIRespositoryFolder);
        }

        private void btnRespositoryBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtRespositoryFolder);
        }

        private void btnIServiceBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtIServiceFolder);
        }

        private void btnServiceBrowser_Click(object sender, EventArgs e)
        {
            SetSavePath(txtServiceFolder);
        }

        private void SetSavePath(TextBox textBox)
        {
            folderBrowser.Description = "请选择源代码保存路径";
            folderBrowser.SelectedPath = textBox.Text;
            if (folderBrowser.ShowDialog(this) == DialogResult.OK)
            {
                string sSelectPath = folderBrowser.SelectedPath;
                textBox.Text = sSelectPath;
                if (textBox.Name == "txtProjectFolder")
                {
                    SetAllSavePath();
                }
            }
        }

        private void SetAllSavePath()
        {
			string projectName = txtProjectNameSpace.Text;
			txtEntityFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".Entity").Replace(@"\\", @"\");
			txtMapFolder.Text = (txtEntityFolder.Text + @"\Map").Replace(@"\\", @"\");
			txtIRespositoryFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".Repository").Replace(@"\\", @"\");
			txtRespositoryFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".IBatisRepository").Replace(@"\\", @"\");
			txtIServiceFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".Service.Contracts").Replace(@"\\", @"\");
			txtServiceFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".Service").Replace(@"\\", @"\");
			txtServiceModelFolder.Text = (txtProjectFolder.Text + @"\" + projectName + ".Service.Model").Replace(@"\\", @"\");

        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            ManageForm form = new ManageForm();
            form.Show();
            this.Hide();
            
        }

        private void btnsave_Click(object sender, EventArgs e)
        {
            SetAttr();

            XmlHelper.Update(info);

        }

		private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			ManageForm form = new ManageForm();
			form.Show();
		}


        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {

            foreach (TreeNode item in e.Node.Nodes)
            {
                item.Checked = e.Node.Checked;
            }

        }

        private void btnEntityToModel_Click(object sender, EventArgs e)
        {


            foreach (TreeNode item in treeView1.Nodes)
            {
                if (item.Checked)
                {

                    info.Columns = new List<ETableInfo>();
                    info.Columns = builder.GetColumns(info.DataBaseName, item.Text);
                    info.TableName = item.Text;
                    richtxtDebug.AppendText("正在生成 " + item.Text + "\r\n ");
                    Application.DoEvents();

                    foreach (TreeNode subItem in item.Nodes)
                    {
                        if (subItem.Checked)
                        {
                            //myList.Find(delegate(Person p) {return p.ID == 1; }); 
                           ETableInfo tableInfo= info.Columns.Find(delegate(ETableInfo t) { return t.ColumnName == subItem.Text; });
                           tableInfo.Select = true;
                        }
                    }

                    string textEditor = textEditorControl.Text+builder.BuilderEntityToModel(info);
                    SetTextEditor(textEditor, "C#");
                }
            }
            this.tabControl1.SelectedTab = this.tabPage3;

        }

        private void btnModelToEntity_Click(object sender, EventArgs e)
        {
            
            foreach (TreeNode item in treeView1.Nodes)
            {
                if (item.Checked)
                {

                    info.Columns = new List<ETableInfo>();
                    info.Columns = builder.GetColumns(info.DataBaseName, item.Text);
                    info.TableName = item.Text;
                    richtxtDebug.AppendText("正在生成 " + item.Text + "\r\n ");
                    Application.DoEvents();

                    foreach (TreeNode subItem in item.Nodes)
                    {
                        if (subItem.Checked)
                        {
                            //myList.Find(delegate(Person p) {return p.ID == 1; }); 
                            ETableInfo tableInfo = info.Columns.Find(delegate(ETableInfo t) { return t.ColumnName == subItem.Text; });
                            tableInfo.Select = true;
                        }
                    }

                    string textEditor = textEditorControl.Text + builder.BuilderEntityToModel(info);
                    SetTextEditor(textEditor, "C#");
                }
            }
            this.tabControl1.SelectedTab = this.tabPage3;

        }

    }
}
